var fileExtensions = [];
var fileids=[];
var saveData ={};
jQuery(document).ready(function () {
    //页面初始化
    formInit();
    //事件注册
    eventInit();
});

//初始化
function formInit() {
    $("#yes_submit").attr("disabled",true);

    if (editData) {
        renderFormData(".layui-form", editData);
        //渲染账户信息，暂时只取一个
        if(isNotEmpty(editData.hcChrgClientAccountList) && editData.hcChrgClientAccountList.length > 0){
            $("#acName").val(editData.hcChrgClientAccountList[0].acName);
            $("#acBank").val(editData.hcChrgClientAccountList[0].acBank);
            $("#acNo").val(editData.hcChrgClientAccountList[0].acNo);
        }
        //渲染附件
        if (isNotEmpty(editData.hcChrgClientAppendList) && editData.hcChrgClientAppendList.length > 0) {
            let clientYYZZHtml = "";
            let clientFRHtml = "";
            let clientJSXHtml = "";
            let clientWTSHtml = "";
            let clientYJXYHtml = "";
            $.each(editData.hcChrgClientAppendList, function (i, item) {
                if('14' == item.type){
                    clientYYZZHtml += `<li class='list-group-item mCustomScrollBox oldFileClass'><span class='clientYYZZbadge' title='${item.id}'>下载</span><span class='view' title='${item.axdpath}'>预览</span><span class='del' title='${item.id}'>删除</span>${item.aname}</li>`;
                }
                if('16' == item.type){
                    clientFRHtml += `<li class='list-group-item mCustomScrollBox oldFileClass'><span class='clientFRbadge' title='${item.id}'>下载</span><span class='view' title='${item.axdpath}'>预览</span><span class='del' title='${item.id}'>删除</span>${item.aname}</li>`;
                }
                if('19' == item.type){
                    clientJSXHtml += `<li class='list-group-item mCustomScrollBox oldFileClass'><span class='clientJSXbadge' title='${item.id}'>下载</span><span class='view' title='${item.axdpath}'>预览</span><span class='del' title='${item.id}'>删除</span>${item.aname}</li>`;
                }
                if('21' == item.type){
                    clientWTSHtml += `<li class='list-group-item mCustomScrollBox oldFileClass'><span class='clientWTSbadge' title='${item.id}'>下载</span><span class='view' title='${item.axdpath}'>预览</span><span class='del' title='${item.id}'>删除</span>${item.aname}</li>`;
                }
                if('22' == item.type){
                    clientYJXYHtml += `<li class='list-group-item mCustomScrollBox oldFileClass'><span class='clientYJXYbadge' title='${item.id}'>下载</span><span class='view' title='${item.axdpath}'>预览</span><span class='del' title='${item.id}'>删除</span>${item.aname}</li>`;
                }
            });
            $('#historyClientYYZZFileDiv>ul').empty().append(clientYYZZHtml);
            $('#historyClientFRFileDiv>ul').empty().append(clientFRHtml);
            $('#historyClientJSXFileDiv>ul').empty().append(clientJSXHtml);
            $('#historyClientWTSFileDiv>ul').empty().append(clientWTSHtml);
            $('#historyClientYJXYFileDiv>ul').empty().append(clientYJXYHtml);
        }
    }

    //大写转换
    inputUpper('#iTaxno');

    //校验税号
    $('#iTaxno').on('change', function () {
        if (!checkTax($('#iTaxno').val())) {
            $('#iTaxno').val('');
            alertMsg('请填写正确的税号！');
        }
    });

    //校验开户行账号
    $('#iBankno').on('change', function () {
        if (!checkBankno($('#iBankno').val())) {
            $('#iBankno').val('');
            alertMsg('请填写正确的银行账号！');
        }
    });

    //校验银行账号
    $('#acNo').on('change', function () {
        if (!checkBankno($('#acNo').val())) {
            $('#acNo').val('');
            alertMsg('请填写正确的银行账号！');
        }
    });

    //校验电话
    $('#cTele').on('change', function () {
        if (checkTeleAndMobile($('#cTele').val())) {
            $('#cTele').val('');
            alertMsg('请填写正确的联系方式！');
        }
    });

    //校验电话
    $('#iTele').on('change', function () {
        if (checkTele($('#iTele').val())) {
            $('#iTele').val('');
            alertMsg('请填写正确的电话！');
        }
    });

    //校验电话
    $('#mobile').on('change', function () {
        if (checkMobile($('#mobile').val())) {
            $('#mobile').val('');
            alertMsg('请填写正确的手机号！');
        }
    });
}

//加载事件
function eventInit() {
    //加载允许上传的文件类型，后缀
    loadAllFileExtensions();

    //clientFileinput('#clientFile','11');//11 客户附件
    //clientFileinput('#contractFile','12');//12 合同附件
    //clientFileinput('#clientZGZSFile','13');//13 《中国民用航空运输销售代理业务资格认可证书》加盖公章的复印件
    clientFileinput('#clientYYZZFile','14');//14 《营业执照或企业法人工商营业执照》加盖公章的复印件
    //clientFileinput('#clientDLXYFile','15');//15 航空公司销售代理协议加盖公章的复印件
    clientFileinput('#clientFRFile','16');//16 公司法人（负责人）身份证明加盖公章的复印件（身份证正反两面）
    //clientFileinput('#clientWXPDGFile','17');//17 航空公司认可的《危险品培训大纲》加盖公章的复印件
    //clientFileinput('#clientWXPZSFile','18');//18 危险品航空运输培训证书（满足《CCAR-276-R1》的培训要求）加盖公章的复印件
    clientFileinput('#clientJSXFile','19');//19 销售代理人对交货员出具的公司介绍信及交货员身份证明加盖公章的复印件
    //clientFileinput('#clientQRHFile','20');//20 航空公司对代理人的交运货物确认函
    clientFileinput('#clientWTSFile','21');//21 授权委托书（如存在委托行为）
    clientFileinput('#clientYJXYFile','22');//22 有关本年签署操作费月结协议的申请

    //勾选承诺书
    $("#promise").on("click", function () {
        if ($(this).is(":checked")== true) {
            $("#yes_submit").attr("disabled",false);
        } else {
            $("#yes_submit").attr("disabled",true);
        }
    });

    //保存
    $("#yes_submit").on("click", function () {
        form.on('submit(yes_submit)', function(data){ //校验必填项
            $("#yes_submit").attr("disabled",true);
            saveData = getFormData('.layui-form');
            saveData.clientStatus=editData.clientStatus;
            saveData.clientNcstatus=editData.clientNcstatus;
            saveData.id=editData.id;
            /*saveData.password = $.trim($("#password").val());
            saveData.confirmWord = $.trim($("#confirmWord").val());*/
            //校验数据
            if (checkClientData(saveData)) {
                layer.msg('保存中...', {
                    time:'-1'
                });
                //依次上传附件，最后保存主体内容
                inputClientYYZZFile();
            }else{
                $("#yes_submit").attr("disabled",false);
            }
        });
    });

    //返回
    $("#cancel_back").on("click", function () {
        parent.layer.closeAll();
        parent.clientTable.reload();
    });

    //下载
    $('.clientYYZZbadge').on('click', function () {
        let title = $(this).attr('title');
        location.href = `${basePath}/hcChrgClientAppend/downLoad/${title}`;
    });
    $('.clientFRbadge').on('click', function () {
        let title = $(this).attr('title');
        location.href = `${basePath}/hcChrgClientAppend/downLoad/${title}`;
    });
    $('.clientJSXbadge').on('click', function () {
        let title = $(this).attr('title');
        location.href = `${basePath}/hcChrgClientAppend/downLoad/${title}`;
    });
    $('.clientWTSbadge').on('click', function () {
        let title = $(this).attr('title');
        location.href = `${basePath}/hcChrgClientAppend/downLoad/${title}`;
    });
    $('.clientYJXYbadge').on('click', function () {
        let title = $(this).attr('title');
        location.href = `${basePath}/hcChrgClientAppend/downLoad/${title}`;
    });

    //附件删除
    $('.del').on('click', function () {
        let ids = $(this).attr('title');
        let _this= $(this);
        if (isEmpty(ids)) {
            return alertMsg('所选附件不存在，请刷新页面');
        }
        let lock = false;//默认未锁定
        layer.confirm('确定删除该附件吗？', {
            btn: ['确定','取消'] //按钮
        }, function(index){
            if (!lock) {
                lock = true;//锁定，防止快速点击触发多次提交
                layer.msg('删除中...', {
                    time: '-1'
                });
                $.hcPostAjax({
                    url: basePath + '/hcChrgClientAppend/' + ids,
                    type: 'delete',
                    success: function (json) {
                        layer.msg('附件删除成功!', {icon: 1, time: 1500}, function () {
                            _this.parent().remove();
                            layer.close(index);
                        });
                    }
                });
            }
        }, function(index){
            layer.close(index);
        });
    });

    //预览
    $('.view').on('click', function () {
        //获取文件的相对路劲，需要配置虚拟路径basePath
        window.open("/filePath/" + $(this).attr('title'));
    });
}

//验证税号 15或者17或者18或者20位字母、数字组成
function checkTax(obj){
    if(/^[A-Z0-9]{15}$|^[A-Z0-9]{17}$|^[A-Z0-9]{18}$|^[A-Z0-9]{20}$/.test(obj)){
        return true;
    }
}

//校验银行卡号 暂时只校验数字
function checkBankno(obj) {
    if (/^\d*$/.test(obj)) {
        return true;
    }
}

//校验电话和手机
function checkTeleAndMobile(obj) {
    /*if (!new RegExp(/^((0\d{2,3})-)(\d{7,8})(-(\d{3,}))?$/).test(obj) &&
        !new RegExp(/^1(3|4|5|6|7|8|9)\d{9}$/).test(obj)) {
        return true;
    }*/
    if (!new RegExp(/^[\d-]+$/).test(obj)) {
        return true;
    }
}

//校验电话
function checkTele(obj) {
    /*if (!new RegExp(/^((0\d{2,3})-)(\d{7,8})(-(\d{3,}))?$/).test(obj)) {
        return true;
    }*/
    if (!new RegExp(/^[\d-]+$/).test(obj)) {
        return true;
    }
}

//校验手机号
function checkMobile(obj) {
    if (!new RegExp(/^1(3|4|5|6|7|8|9)\d{9}$/).test(obj)) {
        return true;
    }
}

function loadAllFileExtensions() {
    $.hcPostAjax({
        url: `${basePath}/clientRegistration/getByFatherCode`,
        type: 'get',
        async: false,
        data: {
            'fatherCode': 'CHAR_FILEEXTENSIONS'
        },
        success: function (json) {
            fileExtensions = [];
            $.each(json, function (i) {
                fileExtensions.push(json[i].codeValue);
            })
        }
    });
}

//保存客户主体内容，并更新附件表cid
function save(fileids) {
    if (isNotEmpty(fileids)) {
        saveData.clientAppendIds = reRepeat(fileids).join(',');
    }
    $.hcPostAjax({
        url : basePath +'/hcChrgClient/updateClientVO',
        type:'post',
        dataType:'json',
        data : saveData,
        success : function(json) {
            layer.msg('保存成功！', {
                icon : 1,
                time : 1500
            }, function() {
                parent.$("#m_search").triggerHandler('click');
                parent.layer.closeAll();
            });
        }
    });
}

//数组去重
function reRepeat(arr){
    let obj={};
    let newArr=[];
    for(var i = 0;i < arr.length;i ++){
        if(!obj[arr[i]]){
            obj[arr[i]]=1;
            newArr.push(arr[i]);
        }
    }
    return newArr;
}

//校验客户数据
function checkClientData(data) {
    var clientResult = false;
    $.hcPostAjax({
        url: basePath + '/hcChrgClient/checkClientData',
        type: 'post',
        dataType: 'json',
        async: false,
        data: data,
        success: function (data) {
            clientResult=true;
        }
    });
    return clientResult;
}

//上传初始化
function clientFileinput(selector,type) {
    $(selector).fileinput({
        language: 'zh',
        uploadUrl: basePath + "/clientRegistration/uploadFile",
        dataType: 'text/json,charset=utf-8',
        browseClass: "btn btn-primary", //按钮样式
        allowedFileExtensions: fileExtensions,
        uploadAsync: false,//同步
        overwriteInitial: false,
        showCancel: false,
        maxFileSize: 700,
        maxFileCount: 5,
        dropZoneEnabled: false,//不允许拖拽
        layoutTemplates: {
            actionUpload: ''
        },
        uploadExtraData: function (previewId, index) {   //额外参数的关键点
            let obj = {
                'type': type //附件类型
            };
            return obj;
        }
    });
}

//《营业执照或企业法人工商营业执照》加盖公章的复印件
function inputClientYYZZFile() {
    fileids=[];//初始化
    let lockYYZZ = false;//默认未锁定
    if (!isEmpty($('#clientYYZZFile').val())) {
        $("#clientYYZZFile").fileinput("upload").on("filebatchuploadsuccess", function (e, data) {
            if (!lockYYZZ) {
                lockYYZZ = true;//锁定，防止触发多次提交
                let result = data.response;
                if (result.code !== null && result.code === 'ok') {
                    if (fileids) {
                        fileids = result.data.concat(fileids);
                    } else {
                        fileids = result.data;
                    }
                    inputClientFRFile();
                } else {
                    showAjaxErrorMsg("上传《营业执照或企业法人工商营业执照》原件的扫描件失败！" + result.msg, function () {
                        $("#clientYYZZFile").fileinput('clear');
                        $("#yes_submit").attr("disabled", false);
                    });
                }
            }
        }).on('fileerror', function (event, data, msg) {
            showAjaxErrorMsg('上传《营业执照或企业法人工商营业执照》原件的扫描件失败！', function () {
                $("#clientYYZZFile").fileinput('clear');
                $("#yes_submit").attr("disabled",false);
            });
        });
    } else {
        inputClientFRFile();
    }
}

//公司法人（负责人）身份证明加盖公章的复印件（身份证正反两面）
function inputClientFRFile() {
    let lockFR = false;//默认未锁定
    if (!isEmpty($('#clientFRFile').val())) {
        $("#clientFRFile").fileinput("upload").on("filebatchuploadsuccess", function (e, data) {
            if (!lockFR) {
                lockFR = true;//锁定，防止触发多次提交
                let result = data.response;
                if (result.code !== null && result.code === 'ok') {
                    if (fileids) {
                        fileids = result.data.concat(fileids);
                    } else {
                        fileids = result.data;
                    }
                    inputClientWTSFile();
                } else {
                    showAjaxErrorMsg("上传公司法人（负责人）身份证明原件的扫描件失败！" + result.msg, function () {
                        $("#clientFRFile").fileinput('clear');
                        $("#clientYYZZFile").fileinput('clear');
                        $("#yes_submit").attr("disabled", false);
                    });
                }
            }
        }).on('fileerror', function (event, data, msg) {
            showAjaxErrorMsg('上传公司法人（负责人）身份证明原件的扫描件失败！', function () {
                $("#clientFRFile").fileinput('clear');
                $("#clientYYZZFile").fileinput('clear');
                $("#yes_submit").attr("disabled",false);
            });
        });
    } else {
        inputClientWTSFile();
    }
}

//授权委托书（如存在委托行为）
function inputClientWTSFile() {
    let lockWTS = false;//默认未锁定
    if (!isEmpty($('#clientWTSFile').val())) {
        $("#clientWTSFile").fileinput("upload").on("filebatchuploadsuccess", function (e, data) {
            if (!lockWTS) {
                lockWTS = true;//锁定，防止触发多次提交
                let result = data.response;
                if (result.code !== null && result.code === 'ok') {
                    if (fileids) {
                        fileids = result.data.concat(fileids);
                    } else {
                        fileids = result.data;
                    }
                    inputClientJSXFile();
                } else {
                    showAjaxErrorMsg("上传授权委托书加盖公章的扫描件失败！" + result.msg, function () {
                        $("#clientWTSFile").fileinput('clear');
                        $("#clientFRFile").fileinput('clear');
                        $("#clientYYZZFile").fileinput('clear');
                        $("#yes_submit").attr("disabled", false);
                    });
                }
            }
        }).on('fileerror', function (event, data, msg) {
            showAjaxErrorMsg('上传授权委托书加盖公章的扫描件失败！', function () {
                $("#clientWTSFile").fileinput('clear');
                $("#clientFRFile").fileinput('clear');
                $("#clientYYZZFile").fileinput('clear');
                $("#yes_submit").attr("disabled",false);
            });
        });
    } else {
        inputClientJSXFile();
    }
}

//销售代理人对交货员出具的公司介绍信及交货员身份证明加盖公章的复印件
function inputClientJSXFile() {
    let lockJSX = false;//默认未锁定
    if (!isEmpty($('#clientJSXFile').val())) {
        $("#clientJSXFile").fileinput("upload").on("filebatchuploadsuccess", function (e, data) {
            if (!lockJSX) {
                lockJSX = true;//锁定，防止触发多次提交
                let result = data.response;
                if (result.code !== null && result.code === 'ok') {
                    if (fileids) {
                        fileids = result.data.concat(fileids);
                    } else {
                        fileids = result.data;
                    }
                    inputClientYJXYFile();
                } else {
                    showAjaxErrorMsg("上传销售代理人对交货员出具的公司介绍信及交货员身份证明加盖公章的扫描件失败！" + result.msg, function () {
                        $("#clientJSXFile").fileinput('clear');
                        $("#clientWTSFile").fileinput('clear');
                        $("#clientFRFile").fileinput('clear');
                        $("#clientYYZZFile").fileinput('clear');
                        $("#yes_submit").attr("disabled", false);
                    });
                }
            }
        }).on('fileerror', function (event, data, msg) {
            showAjaxErrorMsg('上传销售代理人对交货员出具的公司介绍信及交货员身份证明加盖公章的扫描件失败！', function () {
                $("#clientJSXFile").fileinput('clear');
                $("#clientWTSFile").fileinput('clear');
                $("#clientFRFile").fileinput('clear');
                $("#clientYYZZFile").fileinput('clear');
                $("#yes_submit").attr("disabled",false);
            });
        });
    } else {
        inputClientYJXYFile();
    }
}

//有关本年签署操作费月结协议的申请
function inputClientYJXYFile() {
    let lockYJXY = false;//默认未锁定
    if (!isEmpty($('#clientYJXYFile').val())) {
        $("#clientYJXYFile").fileinput("upload").on("filebatchuploadsuccess", function (e, data) {
            if (!lockYJXY) {
                lockYJXY = true;//锁定，防止触发多次提交
                let result = data.response;
                if (result.code !== null && result.code === 'ok') {
                    if (fileids) {
                        fileids = result.data.concat(fileids);
                    } else {
                        fileids = result.data;
                    }
                    //保存主体内容
                    save(fileids);
                } else {
                    showAjaxErrorMsg("上传签署操作费月结协议的申请失败！" + result.msg, function () {
                        $("#clientYJXYFile").fileinput('clear');
                        $("#clientJSXFile").fileinput('clear');
                        $("#clientWTSFile").fileinput('clear');
                        $("#clientFRFile").fileinput('clear');
                        $("#clientYYZZFile").fileinput('clear');
                        $("#yes_submit").attr("disabled", false);
                    });
                }
            }
        }).on('fileerror', function (event, data, msg) {
            showAjaxErrorMsg('上传签署操作费月结协议的申请失败！', function () {
                $("#clientYJXYFile").fileinput('clear');
                $("#clientJSXFile").fileinput('clear');
                $("#clientWTSFile").fileinput('clear');
                $("#clientFRFile").fileinput('clear');
                $("#clientYYZZFile").fileinput('clear');
                $("#yes_submit").attr("disabled",false);
            });
        });
    } else {
        //保存主体内容
        save(fileids);
    }
}

//预览
function getImageWidth(url,callback){
    let img = new Image();
    img.src = url;
    // 如果图片被缓存，则直接返回缓存数据
    if(img.complete){
        callback(img.width, img.height);
    }else{
        // 完全加载完毕的事件
        img.onload = function(){
            callback(img.width, img.height);
        }
    }
}
